import {
	_decorator,
	Component,
	Node,
	Sprite,
	Button,
	SpriteFrame,
	tween,
	Vec3,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Card')
export class Card extends Component {
	@property({ type: Sprite })
	cardSprite: Sprite | null = null;

	private frontSprite: SpriteFrame | null = null;
	private backSprite: SpriteFrame | null = null;
	private isFlipped: boolean = false;
	private isMatched: boolean = false;
	public cardValue: number = -1;
	private gameManager: any = null;

	init(front: SpriteFrame, back: SpriteFrame, value: number, manager: any) {
		this.frontSprite = front;
		this.backSprite = back;
		this.cardValue = value;
		this.gameManager = manager;
		this.isFlipped = false;
		this.isMatched = false;

		this.cardSprite!.spriteFrame = back;

		const button = this.node.getComponent(Button);
		button?.node.on('click', this.onClick, this);
	}

	onClick() {
		if (!this.isFlipped && !this.isMatched) {
			this.gameManager.onCardClicked(this.node);
		}
	}

	flipCard() {
		this.isFlipped = !this.isFlipped;

		tween(this.node)
			.to(0.125, { scale: new Vec3(0, 1, 1) })
			.call(() => {
				this.cardSprite!.spriteFrame = this.isFlipped
					? this.frontSprite
					: this.backSprite;
			})
			.to(0.125, { scale: new Vec3(1, 1, 1) })
			.start();
	}

	setMatched() {
		this.isMatched = true;
		this.node.getComponent(Button)!.interactable = false;

		tween(this.node)
			.to(0.15, { scale: new Vec3(1.1, 1.1, 1) })
			.to(0.15, { scale: new Vec3(1, 1, 1) })
			.start();
	}
}
